package org.nyt.medicalstore.controller;

import org.nyt.medicalstore.model.Supplier;
import org.nyt.medicalstore.service.SupplierService;
import org.nyt.medicalstore.dto.SupplierDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/suppliers")
public class SupplierController {
    @Autowired
    private SupplierService supplierService;

    private SupplierDTO toDTO(Supplier supplier) {
        if (supplier == null) return null;
        SupplierDTO dto = new SupplierDTO();
        dto.setId(supplier.getId());
        dto.setName(supplier.getName());
        dto.setContact(supplier.getContact());
        dto.setAddress(supplier.getAddress());
        return dto;
    }

    @PostMapping
    public SupplierDTO addSupplier(@RequestBody Supplier supplier) {
        return toDTO(supplierService.saveSupplier(supplier));
    }

    @GetMapping("/{id}")
    public SupplierDTO getSupplier(@PathVariable Long id) {
        return toDTO(supplierService.getSupplierById(id));
    }

    @GetMapping
    public List<SupplierDTO> getAllSuppliers() {
        return supplierService.getAllSuppliers().stream().map(this::toDTO).collect(Collectors.toList());
    }

    @DeleteMapping("/{id}")
    public void deleteSupplier(@PathVariable Long id) {
        supplierService.deleteSupplier(id);
    }
}
